#include "EntityNotProcessed.h"
#include "../Commons/Configuration.h"
#include <sstream>
using namespace Entities;

EntityNotProcessed::EntityNotProcessed(EntityType type) :
	IRecordable() {
	this->ID = 0;
	this->booksOffsets = new vector<int> ();
	this->type = type;
}

EntityNotProcessed::EntityNotProcessed(unsigned int id, EntityType type) :
	IRecordable() {

	this->ID = id;
	this->booksOffsets = new vector<int> ();
	this->type = type;

}

vector<int> *EntityNotProcessed::getBooksOffsets() const {
	return booksOffsets;
}

EntityType EntityNotProcessed::getType() const {
	return type;
}

void EntityNotProcessed::setType(EntityType type) {
	this->type = type;
}

void EntityNotProcessed::addOffset(int bookOffset) {
	booksOffsets->push_back(bookOffset);
}

//IRecordable methods

void EntityNotProcessed::fillEntity(char *buffer, unsigned int bufferSize) {

	stringstream* ss = new stringstream(stringstream::in | stringstream::out | stringstream::binary);
	unsigned int numberOfOffsets = 0;
	unsigned int offsetValue = 0;

	//write buffer into stringStream
	ss->seekg(0, ios::beg);
	ss->write(buffer, bufferSize);

	//fill number of offsets
	ss->read((char*) &numberOfOffsets, sizeof(int));


	for (unsigned int i = 0; i < numberOfOffsets; i++) {
		ss->read((char*) &offsetValue, sizeof(int));
		this->booksOffsets->push_back(offsetValue);
	}
}

char* EntityNotProcessed::buildBuffer() {

	stringstream* ss = new stringstream(stringstream::in | stringstream::out | stringstream::binary);
	unsigned int numberOfOffsets = getBooksOffsets()->size();
	unsigned int bufferSize = getBufferSize();
	char* buffer = new char[bufferSize];

	//add header
	ss->seekp(0, ios::end);
	ss->write((char*) &numberOfOffsets, sizeof(int));

	//add offsets
	int offsetValue;
	for (unsigned int i = 0; i < numberOfOffsets; i++) {
		offsetValue = this->getBooksOffsets()->at(i);
		ss->write((char*) &offsetValue, sizeof(int));
	}

	//build buffer
	ss->read(buffer, bufferSize);

	return buffer;

}

unsigned int EntityNotProcessed::getBufferSize() {

	Configuration* config = Configuration::getInstance();
	return config->getBlockSize();
	//return (this->booksOffsets->size() * sizeof(int)) + sizeof(int);
}

unsigned int EntityNotProcessed::getEntityID() {
	return this->ID;
}

void EntityNotProcessed::setEntityID(unsigned int entityID) {
	this->ID = entityID;
}

EntityNotProcessed::~EntityNotProcessed() {
	delete booksOffsets;
}
